package com.chinaV.controller;

import com.chinaV.uitls.DBConnection;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

@WebServlet(value = "/register")
public class Register extends HttpServlet {

    private final DBConnection db = new DBConnection();


    public Register() {
    }

    public boolean userExisit(String username) {
        String sql = "select * from user where username = '" + username + "'";
//        String sql = "select * from user";
        boolean flag = false;
        try {
            ResultSet resultSet = this.db.getSt().executeQuery(sql);
            flag = resultSet.next();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return false;
        }

        return flag;
    }


    public boolean userLogin(String username, String password) {
        if (userExisit(username))
            return false;
        String sql = "insert into user values (null,'" + username + "','" + password + "')";
        boolean flag = false;
        try {
            flag = this.db.getSt().executeUpdate(sql) == 1;

        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return false;
        }

        return flag;
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        // 获取表单数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
//        System.out.println(username);
//        System.out.println(password);
        if (userLogin(username, password)) {
            resp.sendRedirect("/login.jsp");
        } else {
            resp.sendRedirect("/fail.html");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    }

//    public static void main(String[] args) {
//        Register r = new Register();
////        System.out.println(l.userLogin("admin", "admin"));
////        System.out.println(l.userLogin("admin1", "admin"));
//        System.out.println(r.userExisit("admin"));
//
//    }
}

